﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Models;

namespace Data
{
    public class PrivateMessageData:DataBase
    {
        public void Send(PrivateMessage privateMessage)
        {
            var parameters = new List<SqlParameter>
                                 {
                                     new SqlParameter("@Title", privateMessage.Title),
                                     new SqlParameter("@Text", privateMessage.Text),
                                     new SqlParameter("@SendDate", DateTime.Now),
                                     new SqlParameter("@SenderID", privateMessage.Sender.Id),
                                     new SqlParameter("ReceiverID", privateMessage.Receiver.Id),
                                 };
            ExecuteNonQuery("SendPrivateMessage", parameters);
        }

        public List<PrivateMessage> Receive(int? id = null ,int? receiverId = null)
        {
            var parameters = new List<SqlParameter>
                                 {
                                     new SqlParameter("@ReceiverID", receiverId),
                                     new SqlParameter("@ID",id)
                                 };
            var dataTable = ExecuteDataTable("ReceivePrivateMessage", parameters);

            if(dataTable.Rows.Count > 0)
            {
                var messageList = new List<PrivateMessage>();
                var dbUsers = new UsersData();
                foreach (DataRow row in dataTable.Rows)
                {
                    messageList.Add(new PrivateMessage
                                        {
                                            Id = Convert.ToInt32(row["ID"]),
                                            Receiver = dbUsers.GetUsers(Convert.ToInt32(row["ReceiverID"]))[0],
                                            Sender = dbUsers.GetUsers(Convert.ToInt32(row["SenderID"]))[0],
                                            Text = Convert.ToString(row["Text"]),
                                            Title = Convert.ToString(row["Title"]),
                                            SendDate = Convert.ToDateTime(row["SendDate"])
                                        });
                }
                return messageList;

            }
            return null;
        }
    }
}